library(tidyverse)
library(kableExtra)
library(stargazer)

library(sandwich)
library(lmtest)

f_color <- "#1b9e77"
m_color <- "#d95f02"


cvars <- c("age","white","college_grad","newsint_flip","ideo_centered","region_fact",
           "nCandidatesPre","political_knowledge")
match_cvars <- c(cvars,str_c("match_",cvars))

outcomes <- c("external_influence_index",
              "match_postSurvey_partnerInfluencedMe_std",
              "matchChangeRankMyRank1Pre_std","matchChangeThermMyRank1Pre_std")
outcome_order <- c(1:4)

standardize <- function(x){
  x/sd(x,na.rm=T)
}
std_mean <- function(x){
  x/sd(x,na.rm = T)
}



# load individual-level data and add some alter variables
# Rhese files contain identifying information, so the raw data are not provided. 
# The final files created in this block are included in the replication package.  
if(FALSE){
  user_data <- read_csv("data/clean_data.csv") %>%
    left_join(read_csv("2020-03-06-15_24_users.csv") %>% select(code,rematched)) %>% 
    left_join(read_csv("2020-03-06-15_24_users.csv") %>% select(match_id=code,match_rematched=rematched)) %>% 
    filter(chatPostCompleteOnTime==1) %>% 
    left_join(read_csv("data/clean_data.csv") %>% 
                select(match_id=code,match_postSurvey_partnerInfluencedMe=postSurvey_partnerInfluencedMe)) %>% 
    ungroup() %>% 
    mutate(correctly_labeled = !mislabeled & !partnerMislabeled,
           cross_gender_correctly_labeled = !same_gender & correctly_labeled,
           matchChangeRankMyRank1Pre = -1*matchChangeRankMyRank1Pre, #flip for sign consistency
           across(all_of(c("postSurvey_influencedPartner","match_postSurvey_partnerInfluencedMe",
                           "matchChangeRankMyRank1Pre","matchChangeThermMyRank1Pre")),
                  standardize,
                  .names = "{.col}_std"),
           influence_index = rowMeans(cbind(postSurvey_influencedPartner_std,match_postSurvey_partnerInfluencedMe_std,
                                            matchChangeRankMyRank1Pre_std,matchChangeThermMyRank1Pre_std)),
           external_influence_index = rowMeans(cbind(match_postSurvey_partnerInfluencedMe_std,
                                                     matchChangeRankMyRank1Pre_std,matchChangeThermMyRank1Pre_std)),
           across(c(influence_index,external_influence_index),standardize))
  
  user_data %>% 
    select(cvars,match_cvars,outcomes,
           chatID,chatCondition,
           fullCondition,mislabeled,partnerMislabeled,genderF,same_gender,gender,
           guessPartnerGenderCorrect) %>% 
    write_csv("replication/data/user_data.csv")
  
  convergence_data <- read.csv("data/conversation_level_data_with_codes.csv") %>% 
    as_tibble() %>% 
    mutate(cross_gender_correct_labels = ifelse(!same_gender & !mislabeled,1,0),
           same_gender_m = ifelse(same_gender & chatCondition == "M(M)-M(M)",1,0),
           same_gender_f = ifelse(same_gender & chatCondition == "F(F)-F(F)",1,0))
  
  convergence_data <- convergence_data %>% 
    left_join(read_csv("2020-03-06-15_24_users.csv") %>% select(code_m=code,rematched_m=rematched)) %>% 
    left_join(read_csv("2020-03-06-15_24_users.csv") %>% select(code_f=code,rematched_f=rematched)) %>% 
    mutate(across(starts_with("rematched"),function(v) case_when(v==1 ~ 1,is.na(v) ~ 0,TRUE ~ 0)))
  convergence_data %>% 
    select(chatID,mislabeled,
           chatPostCompleteOnTime,starts_with("same_gender"),
           matches("^convergence"),matches("mislabeled$"),
           contains("gap")) %>% 
    write_csv("replication/data/convergence_data.csv")
}

user_data <- read_csv("replication/data/user_data.csv")
convergence_data <- read_csv("replication/data/convergence_data.csv")

user_data %>% select(ends_with("std"),ends_with("index"))

### function to produce: 
#' output df of outcome variable name and label-condition dummy coefficients
#'    - point estimates
#'    - SE (clustered)
#'    - 83% CI (clustered SE)
#'    - 95% CI (clustered SE)

lm_cluster <- function(outcome,df,intercept=FALSE,cvars=NULL,pool_contrasts=FALSE,interact_contrasts=FALSE,same_gender_baseline=FALSE,return.fit = F){
  # make formula
  model_eqtn <- str_c(outcome," ~ fullCondition")
  if(pool_contrasts) model_eqtn <- str_c(outcome," ~ mislabeled + partnerMislabeled + genderF")
  if(interact_contrasts) model_eqtn <- str_c(outcome," ~ mislabeled + partnerMislabeled + genderF + mislabeled:genderF + partnerMislabeled:genderF")
  if(same_gender_baseline) model_eqtn <- str_c(outcome," ~ partnerMislabeled + cross_gender_correctly_labeled")
  if(!is.null(cvars)) model_eqtn <- str_c(model_eqtn," + ",str_c(cvars,collapse = " + "))
  if(!intercept) model_eqtn <- str_c(model_eqtn," + 0")
  
  # run model
  fit <- lm(model_eqtn,data = df)
  if(return.fit) return(fit)
  
  # cluser SEs
  cov_mat <- vcovCL(fit,cluster = df$chatID)
  
  # collect statistics
  stats <- lmtest::coeftest(fit)[,] %>% 
    as_tibble(rownames = "vars") %>% 
    mutate(outcome=outcome,
           nobs=length(fit$resid)) %>% 
    select(outcome,vars,everything())
  
  ci_nocluster95 <- confint(fit,level = 0.95) %>% 
    as_tibble(rownames = "vars") %>% 
    rename(lb95_no_cluster = 2,ub95_no_cluster=3)
  ci_nocluster83 <- confint(fit,level = 0.90) %>% 
    as_tibble(rownames = "vars") %>% 
    rename(lb83_no_cluster = 2,ub83_no_cluster=3)
  
  ci_cluster95 <- lmtest::coefci(fit,vcov. = cov_mat,level = 0.95) %>% 
    as_tibble(rownames = "vars") %>% 
    rename(lb95_cluster = 2,ub95_cluster=3)
  ci_cluster83 <- lmtest::coefci(fit,vcov. = cov_mat,level = 0.90) %>% 
    as_tibble(rownames = "vars") %>% 
    rename(lb83_cluster = 2,ub83_cluster=3)
  
  left_join(stats,ci_nocluster95) %>% 
    left_join(ci_nocluster83) %>% 
    left_join(ci_cluster95) %>% 
    left_join(ci_cluster83)
}


### Figure 2

influence_chat_data <- user_data %>% 
  group_by(chatID) %>% 
  filter(!same_gender) %>% 
  summarise(chat_condition = first(chatCondition),
            mislabeled = max(mislabeled),
            correctly_labeled = 1-mislabeled,
            mislabeled_man = str_detect(chat_condition,"M\\(F\\)"),
            mislabeled_woman = str_detect(chat_condition,"F\\(M\\)"),
            n_correct = sum(guessPartnerGenderCorrect[partnerMislabeled!=1]),
            deceptionWorked = ifelse(max(partnerMislabeled)==0,TRUE,!guessPartnerGenderCorrect[partnerMislabeled==1]),
            across(all_of(outcomes),function(v) v[gender == "M"] - v[gender == "F"])) %>% 
  left_join(convergence_data) # for covariates


fits <- lapply(outcomes,function(y) lm(str_c(y,"~ + mislabeled_man + mislabeled_woman"),data=influence_chat_data %>% 
                                         mutate(mislabeled_man = ifelse(mislabeled_man,1,0),
                                                mislabeled_woman = ifelse(mislabeled_woman,1,0))))
names(fits) <- outcomes
lapply(fits,summary)

tidy_twoCIs <- function(fit,conf.level1,conf.level2){
  tidy1 <- broom::tidy(fit,conf.int=T,conf.level = conf.level1)
  tidy2 <- broom::tidy(fit,conf.int=T,conf.level = conf.level2)
  
  left_join(tidy1,
            tidy2 %>% select(term,conf.low2=conf.low,conf.high2=conf.high))
}

influence_gap.results <- map_df(fits,tidy_twoCIs,conf.level1=.95,conf.level2=.90,.id = "outcome") %>% 
  mutate(outcome = str_remove(outcome,"_std")) %>% 
  left_join(readxl::read_xlsx("replication/data/condition_descriptions.xlsx",sheet="outcomes")) %>% 
  mutate(across(c(contains("outcome_description")),
                function(v) str_remove_all(v,"\\r")),
         outcome_description = factor(outcome_description,levels=unique(outcome_description))) %>%
  mutate(effect_description = case_when(
    str_detect(term,"mislabeled_man") ~ "Effect of Mislabeling\n Man's Gender",
    str_detect(term,"mislabeled_woman") ~ "Effect of Mislabeling\n Woman's Gender",
    TRUE ~ "Influence Gap in\nCorrectly Labeled\nConversations"),
    effect_description = factor(effect_description,levels = unique(effect_description)))

fits2 <- lapply(outcomes,function(y) lm(str_c(y,"~ 0 + correctly_labeled + mislabeled_man + mislabeled_woman"),data=influence_chat_data %>% 
                                          mutate(mislabeled_man = ifelse(mislabeled_man,1,0),
                                                 mislabeled_woman = ifelse(mislabeled_woman,1,0))))
names(fits2) <- outcomes
lapply(fits2,summary)

influence_gap_levels.results <- map_df(fits2,tidy_twoCIs,conf.level1=.95,conf.level2=.90,.id = "outcome") %>% 
  mutate(outcome = str_remove(outcome,"_std")) %>% 
  left_join(readxl::read_xlsx("replication/data/condition_descriptions.xlsx",sheet="outcomes")) %>% 
  mutate(across(c(contains("outcome_description")),
                function(v) str_remove_all(v,"\\r")),
         outcome_description = factor(outcome_description,levels=unique(outcome_description))) %>%
  mutate(effect_description = case_when(
    str_detect(term,"mislabeled_man") ~ "Mislabeled\nMan",
    str_detect(term,"mislabeled_woman") ~ "Mislabeled\nWoman",
    TRUE ~ "Correctly\nLabeled"),
    effect_description = factor(effect_description,levels = unique(effect_description))) %>% 
  left_join(influence_gap.results %>% select(outcome,term,p.value_contrast=p.value)) %>% 
  mutate(stars = case_when(p.value_contrast <= 0.01 ~ "**",
                           p.value_contrast <= 0.05 ~ "*",
                           p.value_contrast <= 0.10 ~ "",
                           TRUE ~ ""))

influence_gap_levels.results %>% 
  ggplot(aes(x=effect_description,y=estimate,color=effect_description)) + 
  geom_point() + 
  geom_errorbar(aes(ymin=conf.low,ymax=conf.high),width=.1,alpha=.5) +
  geom_errorbar(aes(ymin=conf.low2,ymax=conf.high2),width=0,size=1,alpha=1) +
  geom_hline(yintercept=0) +
  facet_wrap(~outcome_description_gap,scales = "fixed",ncol = 2) + 
  theme_bw() + 
  labs(x="\nConversation Description",
       y="Influence Gap\n(Male Influence minus Female Influence)") + 
  theme(#axis.text.x = element_text(size = 11),
    legend.position = "none",
    plot.title = element_text(hjust = .5),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    strip.background = element_blank(),
    panel.border = element_rect(colour = "black", fill = NA),
    strip.text.x = element_text(face="bold"),
    text = element_text(size = 24),
    axis.text.x = element_text(size=23)) + 
  geom_text(aes(label=stars),nudge_x = .1,color="black",size=5) + 
  scale_color_manual(values = c("black",m_color,f_color),
                     breaks = levels(influence_gap_levels.results$effect_description)) + 
  geom_blank() 
ggsave("replication/output/gap_means_and_stars.png",width = 13,height = 10,dpi = 300)

### Figure 3
convergence_outcomes <- c("convergence_all",
                          "convergence_biden","convergence_sanders","convergence_warren",
                          "convergence_bloomberg","convergence_buttigieg","convergence_klobuchar",
                          "convergence_gabbard","convergence_steyer")

convergence_data %>% 
  filter(chatPostCompleteOnTime==1,!same_gender,!is.na(convergence_all)) %>% 
  select(chatID,male_mislabeled,female_mislabeled,mislabeled,
         starts_with("same_gender"),
         contains("gap")) %>% 
  mutate(mislabel_status = case_when(
    male_mislabeled==1 ~ "Mislabeled Man",
    female_mislabeled==1 ~ "Mislabeled Woman",
    same_gender_m==1 ~ "Correct Labels\nMan-Man",
    same_gender_f==1 ~ "Correct Labels\nWoman-Woman",
    mislabeled==0 ~ "Correct Labels"),
    mislabel_status = factor(mislabel_status) %>% relevel("Correct Labels")) %>% 
  group_by(mislabel_status,mislabeled) %>% 
  pivot_longer(cols = contains("gap")) %>% 
  mutate(t = case_when(str_detect(name,"post") ~ 1,
                       str_detect(name,"pre") ~ 0),
         cand = str_extract(name,"_(.*)") %>% str_sub(start=6)) %>% 
  filter(!is.na(value)) %>% 
  group_by(chatID,cand) %>% 
  filter(n()==2) %>% 
  group_by(mislabel_status,t,mislabeled) %>% 
  summarise(sd = sd(abs(value),na.rm = T)/sqrt(n()),
            value = mean(abs(value),na.rm=T),
            lb90 = value - 1.64*sd,
            ub90 = value + 1.64*sd,
            lb = value - 1.96*sd,
            ub = value + 1.96*sd) %>% 
  ggplot(aes(x=t,y=value,color=mislabel_status,
             ymin = lb,ymax=ub)) + 
  geom_point(position = position_dodge(width=.3)) + geom_line(position = position_dodge(width=.3)) +   
  geom_errorbar(alpha=.4,width=.3,position = position_dodge(width=.3),linetype="solid") + 
  geom_errorbar(aes(ymin=lb90,ymax=ub90),width=0,size=1,position = position_dodge(width=.3)) + 
  labs(x="",
       color=NULL,
       title = "Thermometer Rating Gaps\nAcross All Candidates",y=""
  ) + 
  scale_linetype(guide = "none") + 
  scale_x_continuous(breaks = c(0,1),
                     labels=c("Pre\nConversation","Post\nConversation"),
                     limits=c(-.3,1.3)) + 
  theme_bw() + 
  theme(
    legend.position = "none",
    plot.title = element_text(hjust = .5),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    strip.background = element_blank(),
    panel.border = element_rect(colour = "black", fill = NA),
    strip.text.x = element_text(face="bold"),
    text = element_text(size = 20)) + 
  theme(legend.position = c(.6,.9)) + 
  scale_color_manual(values = c("black",m_color,f_color)) -> convergence_levels_plot
convergence_levels_plot


cvg_cvars <- c() 
fits_baseline <- lapply(convergence_outcomes,function(y) lm(str_c(y,"~ mislabeled_man + mislabeled_woman + ",ifelse(is.null(cvg_cvars),"1",str_c(cvg_cvars,collapse = "+ "))),
                                                            data=influence_chat_data))
fits_baseline_levels <- lapply(convergence_outcomes,function(y) lm(str_c(y,"~ correctly_labeled + mislabeled_man + mislabeled_woman + ",ifelse(is.null(cvg_cvars),"0",str_c(cvg_cvars,collapse = "+ "))),
                                                                   data=influence_chat_data %>% mutate(mislabeled_man = ifelse(mislabeled_man,1,0),
                                                                                                       mislabeled_woman = ifelse(mislabeled_woman,1,0))))
names(fits_baseline) <- convergence_outcomes
stargazer(fits_baseline,type="text",star.cutoffs = c(0.05,0.01,0.001),
          column.labels = names(fits_baseline) %>% str_replace_all("_","."),
          df=FALSE)


fits_baseline[[1]] %>% 
  {cbind(est=coef(.),est=confint(.),est=confint(.,level = .90))} %>% 
  as_tibble(rownames = "var") %>% 
  mutate(across(where(is.numeric),function(x) -1*x)) %>% 
  mutate(label = c("Convergence in\nCross-Gender Conversations",
                   "Effect of Mislabeling\nthe Man's Gender",
                   "Effect of Mislabeling\nthe Woman's Gender")) %>% 
  mutate(levels = case_when(row_number()>1 ~ est + est[1],
                            TRUE ~ est),
         levels.low = case_when(var!="(Intercept)" ~ `2.5 %` - est + levels,
                                TRUE ~ NA_real_),
         levels.high = case_when(var!="(Intercept)" ~ `97.5 %` - est + levels,
                                 TRUE ~ NA_real_)) %>% 
  filter(var != "(Intercept)") %>% 
  ggplot(aes(x=label,y=est,ymin=`2.5 %`,ymax=`97.5 %`,color = c(f_color,m_color))) + 
  geom_point() + geom_errorbar(width=.1) + geom_errorbar(aes(ymin=`5 %`,ymax=`95 %`),width=0,size=1) + 
  labs(x="",
       y="",
       title = "Treatment Effects on Changes\nin Thermometer Rating Gaps") + 
  geom_hline(yintercept = 0) + 
  theme_bw()+ 
  theme(
    legend.position = "none",
    plot.title = element_text(hjust = .5),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    strip.background = element_blank(),
    panel.border = element_rect(colour = "black", fill = NA),
    strip.text.x = element_text(face="bold"),
    text = element_text(size = 20)) + 
  scale_color_manual(values = c(m_color,f_color)) -> convergence_effects_plot
convergence_effects_plot
gridExtra::arrangeGrob(convergence_levels_plot + 
                         labs(y="Mean Absolute Difference in\nThermometer Ratings for the Same Candidate\nPre- and Post-Conversation") + 
                         theme(axis.text.x = element_text(size = 23), 
                               axis.title.y = element_text(size=23)),
                       convergence_effects_plot + 
                         labs(y="Change in Thermometer Rating Gap\nRelative to Control") + 
                         theme(axis.text.x = element_text(size = 23), 
                               axis.title.y = element_text(size=23)),
                       nrow=1,widths = c(.43,.6)) -> combo_plot

ggsave(plot = combo_plot,"replication/output/convergence_twopanel.png",width = 13,height = 10,dpi = 300)


### Figure 4

### function to produce: 
#' output df of outcome variable name and label-condition dummy coefficients (note different lower bound CI)
#'    - point estimates
#'    - SE (clustered)
#'    - 90% CI (clustered SE)
#'    - 95% CI (clustered SE)

lm_cluster <- function(outcome,df,intercept=FALSE,cvars=NULL,pool_contrasts=FALSE,interact_contrasts=FALSE,same_gender_baseline=FALSE,return.fit = F){
  # make formula
  model_eqtn <- str_c(outcome," ~ fullCondition")
  if(pool_contrasts) model_eqtn <- str_c(outcome," ~ mislabeled + partnerMislabeled + genderF")
  if(interact_contrasts) model_eqtn <- str_c(outcome," ~ mislabeled + partnerMislabeled + genderF + mislabeled:genderF + partnerMislabeled:genderF")
  if(same_gender_baseline) model_eqtn <- str_c(outcome," ~ partnerMislabeled + cross_gender_correctly_labeled")
  if(!is.null(cvars)) model_eqtn <- str_c(model_eqtn," + ",str_c(cvars,collapse = " + "))
  if(!intercept) model_eqtn <- str_c(model_eqtn," + 0")
  
  # run model
  fit <- lm(model_eqtn,data = df)
  if(return.fit) return(fit)
  
  # cluser SEs
  cov_mat <- vcovCL(fit,cluster = df$chatID)
  
  # collect statistics
  stats <- lmtest::coeftest(fit)[,] %>% 
    as_tibble(rownames = "vars") %>% 
    mutate(outcome=outcome,
           nobs=length(fit$resid)) %>% 
    select(outcome,vars,everything())
  
  stats_cl <- lmtest::coeftest(fit,vcov. = cov_mat)[,] %>% 
    as_tibble(rownames = "vars") %>% 
    mutate(outcome=outcome) %>% 
    select(outcome,vars,p_cluster = `Pr(>|t|)`)
  
  ci_nocluster95 <- confint(fit,level = 0.95) %>% 
    as_tibble(rownames = "vars") %>% 
    rename(lb95_no_cluster = 2,ub95_no_cluster=3)
  ci_nocluster90 <- confint(fit,level = 0.90) %>% 
    as_tibble(rownames = "vars") %>% 
    rename(lb90_no_cluster = 2,ub90_no_cluster=3)
  
  ci_cluster95 <- lmtest::coefci(fit,vcov. = cov_mat,level = 0.95) %>% 
    as_tibble(rownames = "vars") %>% 
    rename(lb95_cluster = 2,ub95_cluster=3)
  ci_cluster90 <- lmtest::coefci(fit,vcov. = cov_mat,level = 0.90) %>% 
    as_tibble(rownames = "vars") %>% 
    rename(lb90_cluster = 2,ub90_cluster=3)
  
  left_join(stats,stats_cl) %>% 
    left_join(ci_nocluster95) %>% 
    left_join(ci_nocluster90) %>% 
    left_join(ci_cluster95) %>% 
    left_join(ci_cluster90)
}

#check
lm_cluster("external_influence_index",interact_contrasts=T,user_data)


#################################################
### Mislabeling treatment effects among males ###
#################################################

male_cg_contrasts.df <- user_data %>% filter(!genderF) %>% 
  mutate(fullCondition=relevel(factor(fullCondition),"F(F)-M(M)_M(M)"))

male_cg_contrasts.results <- map_df(outcomes,lm_cluster,df=male_cg_contrasts.df,intercept=FALSE,cvars=NULL) %>% 
  mutate(outcome = str_remove(outcome,"_std")) %>% 
  left_join(readxl::read_xlsx("replication/data/condition_descriptions.xlsx",sheet="treatments")) %>% 
  left_join(readxl::read_xlsx("replication/data/condition_descriptions.xlsx",sheet="outcomes")) %>% 
  mutate(across(c(long_label,contains("outcome_description")),
                function(v) str_remove_all(v,"\\r")),
         effect_description = case_when(
           partnerMislabeled==1 ~ "Effect of Mislabeling\n Woman's Gender\n(Mislabeling Alter)",
           mislabeled==1 ~ "Effect of Mislabeling\n Man's Gender\n(Mislabeling Ego)",
           TRUE ~ "Man's Influcence on Woman\nAccurate Gender Labels\n(Control Baseline)"
         ),
         effect_description = factor(effect_description,levels = (unique(effect_description))),
         outcome_description_man_ego = factor(outcome_description_man_ego,
                                              levels = unique(outcome_description_man_ego)[outcome_order]),
         color = m_color)

### Mislabeling treatment effects among females
female_cg_contrasts.df <- user_data %>% filter(genderF) %>% 
  mutate(fullCondition=relevel(factor(fullCondition),"F(F)-M(M)_F(F)"))

female_cg_contrasts.results <- map_df(outcomes,lm_cluster,df=female_cg_contrasts.df,intercept=FALSE,cvars = NULL) %>% 
  mutate(outcome = str_remove(outcome,"_std")) %>% 
  filter(vars != "(Intercept)") %>% 
  left_join(readxl::read_xlsx("replication/data/condition_descriptions.xlsx",sheet="treatments")) %>% 
  left_join(readxl::read_xlsx("replication/data/condition_descriptions.xlsx",sheet="outcomes")) %>% 
  mutate(across(c(long_label,contains("outcome_description")),
                function(v) str_remove_all(v,"\\r")),
         effect_description = case_when(
           partnerMislabeled==1 ~ "Effect of Mislabeling\n Man's Gender\n(Mislabeling Alter)",
           mislabeled==1 ~ "Effect of Mislabeling\n Woman's Gender\n(Mislabeling Ego)",
           TRUE ~ "Woman's Influcence on Man\nAccurate Gender Labels\n(Control Baseline)"
         ),
         effect_description = factor(effect_description,levels = (unique(effect_description))),
         outcome_description_woman_ego = factor(outcome_description_woman_ego,
                                                levels = unique(outcome_description_woman_ego)[outcome_order]),
         color=f_color)

### combined plot ###

female_contrasts <- lm_cluster("external_influence_index",
                               df=bind_rows(female_cg_contrasts.df %>% filter(!same_gender),
                                            male_cg_contrasts.df %>% filter(same_gender)),
                               intercept=TRUE,cvars = NULL)
male_contrasts <- lm_cluster("external_influence_index",
                             df=bind_rows(male_cg_contrasts.df %>% filter(!same_gender),
                                          female_cg_contrasts.df %>% filter(same_gender)),
                             intercept=TRUE,cvars = NULL)

all.results <- bind_rows(male_cg_contrasts.results %>% mutate(gender = "Men"),
                         female_cg_contrasts.results %>% mutate(gender = "Women")) %>% 
  mutate(effect_description_all = case_when(mislabeled==1 ~ "Effect of Mislabeling on\nEgo's Influence on Alter",
                                            partnerMislabeled==1 ~ "Effect of Mislabeling on\nAlter's Influence on Ego",
                                            same_gender==1 ~ "",
                                            TRUE ~ NA_character_),
         gender_egoML = case_when(partnerMislabeled==1 & gender == "Men" ~ "Women",
                                  partnerMislabeled==1 & gender == "Women" ~ "Men",
                                  TRUE ~ gender),
         lb95 = ifelse(gender == "Both",lb95_cluster,lb95_no_cluster),
         ub95 = ifelse(gender == "Both",ub95_cluster,ub95_no_cluster),
         lb90 = ifelse(gender == "Both",lb90_cluster,lb90_no_cluster),
         ub90 = ifelse(gender == "Both",ub90_cluster,ub90_no_cluster),
         gender = factor(gender,levels = unique(gender)),
         gender_egoML = factor(gender_egoML,levels = unique(gender))) %>% 
  left_join(select(bind_rows(female_contrasts,male_contrasts),
                   vars,p_cluster_contrast=p_cluster)) %>% 
  mutate(stars = case_when(p_cluster_contrast <0.05 ~ "*",
                           p_cluster_contrast <0.01 ~ "**",
                           p_cluster_contrast <0.001 ~ "***",
                           TRUE ~ ""))


all.results %>% 
  filter(!(vars %in% c("genderFTRUE","(Intercept)")),
         outcome == "external_influence_index",
         gender_egoML!="Both") %>% 
  mutate(partner_gender = case_when(same_gender==1 & gender == "Men" ~ "Men",
                                    same_gender==1 & gender == "Women" ~ "Women",
                                    same_gender==0 & gender == "Men" ~ "Women",
                                    same_gender==0 & gender == "Women" ~ "Men"),
         facet_label = case_when(partner_gender == "Men" ~ "Influence on Men",
                                 partner_gender == "Women" ~ "Influence on Women"),
         facet_label = factor(facet_label,levels=unique(facet_label)),
         axis_label = case_when(gender=="Women" & partnerMislabeled==1 ~ "Women's\nInfluence on\nMislabeled Men",
                                gender=="Men" & mislabeled==1 ~ "Mislabeled Men's\nInfluence on\nWomen",
                                gender=="Men" & partnerMislabeled==1 ~ "Men's\nInfluence on\nMislabeled Women",
                                gender=="Women" & mislabeled==1 ~ "Mislabeled Women's\nInfluence on\nMen",
                                gender=="Women" & same_gender==1 ~ "Women's\nInfluence on\nWomen",
                                gender=="Men" & same_gender==1 ~ "Men's\nInfluence on\nMen",
                                gender=="Women" & chat_correctly_labeled==1 & same_gender==0 ~ "Women's\nInfluence on\nMen",
                                gender=="Men" & chat_correctly_labeled==1 & same_gender==0 ~ "Men's\nInfluence on\nWomen",
         ),
         color_label = chatCondition) %>% 
  arrange(order) %>% 
  mutate(axis_label = factor(axis_label,levels=unique(axis_label))) %>% 
  ggplot(aes(x=axis_label,y=Estimate,color = color_label)) + 
  geom_point(position = position_dodge(width = .5)) + 
  geom_errorbar(aes(ymin=lb95_cluster,ymax=ub95_cluster),width=.1,alpha=.5,position = position_dodge(width = .5)) +
  geom_errorbar(aes(ymin=lb90_cluster,ymax=ub90_cluster),width=0,size=1,alpha=1,position = position_dodge(width = .5)) +
  geom_text(aes(label = stars),nudge_x = .1,color="black") + 
  geom_hline(yintercept=0) + 
  geom_vline(xintercept = 1.5,color="grey") + 
  facet_wrap(~facet_label,scales = "free_x",nrow=2) +
  labs(x="",y="Influence Index",
       title = "Individual-Level Influence") + 
  guides(color="none") + 
  theme_bw() + 
  theme(
    legend.position = "bottom",
    plot.title = element_text(hjust = .5),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.spacing = unit(7, "lines"),
    plot.margin = unit(c(t=1, r=1, b=7, l=1), "lines"),
    strip.background = element_blank(),
    panel.border = element_rect(colour = "black", fill = NA),
    strip.text.x = element_text(face="bold"),
    text = element_text(size = 20)) + 
  scale_color_manual(values = c("black",m_color,f_color,"orange","purple"),
                     breaks = c("F(F)-M(M)","F(F)-M(F)","F(M)-M(M)","M(M)-M(M)","F(F)-F(F)"))

ggsave(filename = "replication/output/individual_level_influence_levels.png",height = 12,width = 9,dpi = 300)  
